package com.book.lizhi.database;

import java.util.Set;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.book.lizhi.model.ArticleModel;
import com.book.lizhi.model.BaseModel;
import com.book.lizhi.model.BookshelfModel;

public class AppDatabaseHelper extends SQLiteOpenHelper {

	public AppDatabaseHelper(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);

	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		createTable(db, AppDatabase.BOOK_TABLE_NAME, BookshelfModel.class.getName());
		createTable(db, AppDatabase.FAV_TABLE_NAME, ArticleModel.class.getName());
	}

	private void createTable(SQLiteDatabase db, String tableName, String className) {
		try {
			StringBuffer buffer = new StringBuffer();
			JSONObject object = (JSONObject) JSON.toJSON(Class.forName(className).newInstance());
			Set<String> keySet = object.keySet();
			buffer.append("CREATE TABLE IF NOT EXISTS " + tableName + "(" + "_id INTEGER PRIMARY KEY AUTOINCREMENT");
			for (String property : keySet) {
				buffer.append(", " + property + " TEXT");
			}
			buffer.append(")");
			db.execSQL(buffer.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		if (oldVersion < newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + AppDatabase.BOOK_TABLE_NAME);
			db.execSQL("DROP TABLE IF EXISTS " + AppDatabase.FAV_TABLE_NAME);
			onCreate(db);
		}
	}

}
